package com.acooly.module.openapi.client.provider.baofup;

import com.acooly.module.openapi.client.api.notify.ApiServiceClientServlet;
import com.acooly.module.openapi.client.api.transport.HttpTransport;
import com.acooly.module.openapi.client.api.transport.Transport;
import com.acooly.module.openapi.client.provider.baofup.enums.BaoFuPServiceEnum;
import com.acooly.module.openapi.client.provider.baofup.notify.BaoFuPApiServiceClientServlet;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

import java.util.List;


@EnableConfigurationProperties({OpenAPIClientBaoFuPProperties.class})
@ConditionalOnProperty(value = OpenAPIClientBaoFuPProperties.PREFIX + ".enable", matchIfMissing = true)
@ComponentScan
public class OpenAPIClientBaoFuPConfigration {

    @Autowired
    private OpenAPIClientBaoFuPProperties openAPIClientBaoFuPProperties;

    @Bean("baoFuPHttpTransport")
    public Transport BaoFuPHttpTransport() {
        HttpTransport httpTransport = new HttpTransport();
        httpTransport.setGateway(openAPIClientBaoFuPProperties.getGatewayUrl());
        httpTransport.setConnTimeout(String.valueOf(openAPIClientBaoFuPProperties.getConnTimeout()));
        httpTransport.setReadTimeout(String.valueOf(openAPIClientBaoFuPProperties.getReadTimeout()));
        return httpTransport;
    }

    /**
     * 宝付SDK-servlet注册
     *
     * @return
     */
    @Bean
    public ServletRegistrationBean getBaoFuPApiSDKServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean();
        BaoFuPApiServiceClientServlet apiServiceClientServlet = new BaoFuPApiServiceClientServlet();
        bean.setServlet(apiServiceClientServlet);
        bean.addInitParameter(ApiServiceClientServlet.NOTIFY_DISPATCHER_BEAN_NAME_KEY, "baoFuPNotifyHandlerDispatcher");
        List<String> urlMappings = Lists.newArrayList();       //网关异步通知地址
        urlMappings.add(BaoFuPConstants.NOTIFY_SUB_URL + BaoFuPServiceEnum.PROTOCOL_PAY.getCode());//访问，可以添加多个
        bean.setUrlMappings(urlMappings);
        bean.setLoadOnStartup(3);
        return bean;
    }
}
